import React, { Dispatch, ReactNode, SetStateAction, useEffect, useState } from 'react';
import { debounce } from '@/utils';
import { BusinessTaskMap, IBusinessName, IBusinessStatus, ICustomerMembers, useBusiness } from '@/views/Context/BusinessContext';
import { ScreenSyncStateProps, useScreenSync } from './ScreenSyncContext';
import { useDispatch, useSelector } from 'react-redux';
import { getAgentBindBizScenario, getAgentProfile, getAllBizScenario, agentIsBoundBizscenarios, agentIsCheckInBizscenarios, agentIdIsExistence, getAgentNameIsRobot } from '@/api';
import { setScreenStream } from '@/store/reducers/stream';
import { transfer, inviteOther, agentScreenShare, screenshot, screenMark, stopScreenShare, stopScreenMark, hangup, transferBizscenario } from '@/utils/lib';
import { clearChatRecord, setChatRecord } from '@/store/reducers/chatRecord';
import { uploadFileWithBlob, compareFace } from '@/api';
import { dataURItoBlob } from '@/utils';
import { useStream } from './StreamContext';
import { createScreenContainer } from '../ScreenStream';
import { endScreenShare, sendCustomizeMessage } from './utils/requestBusiness';
import useSyncState from '../hooks/useSyncState';
import { getTools, updateToolsText } from '@/conf';
import Message from '@/utils/message';
import store from '@/store';
import AgentService from '@/modules/Agent';
import { useTranslation } from 'react-i18next';
import { IOperationName, IOperationType } from '@/modules/interface';
import { isChrome104Plus } from '../../utils/userAgent';

interface IMenuProps {
	fields: any[];
	modalTitle: string;
	endSessionView: boolean;
	showTransfer: boolean;
	transferError: boolean;
	inviteAgentIsRobot: boolean;
	showSendCommand: boolean;
	searchAgentBindBizScenario: ISearchScenarioProps[];
	inviteMode: 'invite' | 'transfer';
	screenShareStatus: IScreenSyncStatus | null;
	sendCommandModalType: IBusinessName | null;
	showCustomerRoleOrName: boolean;
	inviteAgentError: string;
	groupSkillError: string;
	bizScenarioTransferToScenErrorText: string;
	bizScenarioTransferToAgentErrorText: string;
	bizScenarioTransferGroupSkill: string;
	transferAgentIdErrorText: string;
	showVariableView: boolean;
	showKnowledgeBase: boolean;
}

enum IToolsProps {
	END_SESSION = 'end-session',
	SCREEN_SHARE = 'screen-share',
	SCREEN_MARK = 'screen-mark',
	TRANSFER = 'transfer',
	INVITE = 'invite',
	SCREEN_SYNC = 'start-screen-sync',
	GET_GEO_LOCATION = 'get-geo-location',
	ID_CARD_COMPARE = 'idcard-compare',
	RECORD_SCREEN = 'record-screen',
	FACE_COMPARE = 'face-compare',
	SNAP_SHOT = 'snapshot',
	SCREEN_SHOT = 'screen-shot',
	SCANNER_CODE = 'scanner-code',
	SEND_LINK = 'send-link',
	SEND_VIDEO = 'send-video',
	SEND_FORM = 'send-form',
	SEND_SIGN = 'send-sign',
	SEND_PDF = 'send-pdf',
	SEND_CARD_COLLECTION = 'send-card-collection',
	SHARED_WHITEBOARD = 'shared-whiteboard',
	SHARED_PDF = 'shared-pdf',
	SEND_VARIABLE_COLLECTION = 'send-variable-collection',
	TRANSCRIPT_OF_TESTIMONY = 'transcript-of-testimony',
	SEND_VIDEO_COLLECTION = 'send-video-collection',
	TTS_BROADCAST = 'tts-broadcast',
	SEND_KNOWLEDGE_BASE = 'knowledge-base'
}

enum IScreenSyncStatus {
	START = 'start',
	STOP = 'stop',
	MARK = 'mark'
}

const audioSendBusiness = [
	IBusinessName.GET_GEO_LOCATION,
	IBusinessName.SCREEN_SHARE,
	IBusinessName.RECORD_SCREEN,
	IBusinessName.SEND_LINK,
	IBusinessName.SEND_SIGN,
	IBusinessName.REGIONAL_SCREEN_RECORDING
];

interface ISearchScenarioProps {
	value?: string;
	label?: string;
	id?: number;
}

interface IOuterFunc {
	hangUp: () => void;
}

const defaultOutFunc: IOuterFunc = {
	hangUp: function () {}
};

const defaultInitialState: IMenuProps = {
	modalTitle: '',
	fields: [],
	endSessionView: false,
	transferError: false,
	showTransfer: false,
	showSendCommand: false,
	inviteAgentIsRobot: false,
	searchAgentBindBizScenario: [],
	inviteMode: 'invite',
	groupSkillError: '',
	screenShareStatus: null,
	sendCommandModalType: null,
	showCustomerRoleOrName: false,
	inviteAgentError: '',
	bizScenarioTransferToScenErrorText: '',
	bizScenarioTransferToAgentErrorText: '',
	bizScenarioTransferGroupSkill: '',
	transferAgentIdErrorText: '',
	showVariableView: false,
	showKnowledgeBase: false
};

export interface TabsProps {
	label: string;
	key: string;
}

export interface ChiefsProps {
	code: number;
	data: number | any;
}

type TransferType = 'default' | 'agent' | 'groupSkill';
interface IBizScenarioTransfer {
	mode: TransferType;
	transferScene?: number;
	agentName?: string;
	groups: { id: number; name: string }[] | null;
}

const MenuContext = React.createContext<
	| {
			menuState: IMenuProps;
			onEndSession: (type?: string) => void;
			setMenuState: Dispatch<SetStateAction<IMenuProps>>;
			chooseBusiness: (type: string) => void;
			setOuterFuc: Dispatch<SetStateAction<IOuterFunc> | any>;
			onChangeBizScenario: (data: any) => void;
			bizScenarioTransfer: (data: IBizScenarioTransfer) => void;
			tools: () => any[];
			setTools: (tools: any) => void;
			chiefs: () => ChiefsProps[];
			setChiefs: (chiefs: ChiefsProps[]) => void;
			serviceMonitoringView: () => boolean;
			setServiceMonitoring: (serviceMonitoringView: boolean) => void;
			mainContent: () => string;
			setMainContent: (mainContent: string) => void;
			roomId: () => string;
			setRoomId: (roomId: string) => void;
			isJoinSession: () => boolean;
			setIsJoinSession: (isJoinSession: boolean) => void;
			loading: () => boolean;
			setLoading: (loading: boolean) => void;
			inviteAgent: (data: { agentName?: string; groups: { id: number; name: string }[] | null; mode: 'agent' | 'groupSkill' }) => void;
			agentTransfer: (data: IBizScenarioTransfer) => void;
	  }
	| undefined
>(undefined);
MenuContext.displayName = 'MenuContext';

const MenuProvider = ({ children }: { children: ReactNode }) => {
	const { t } = useTranslation();
	const { reuqestPages, screenSyncState, setScreenSyncState } = useScreenSync();
	const { screenStream, streams, audioStreams } = useStream();
	const { session, agent, setting } = useSelector((state: any) => state);
	const [menuState, setMenuState] = useState<IMenuProps>(defaultInitialState);
	const { getCustomerMembers, sendBusiness, screenId, setScreenId, startWhiteBoard } = useBusiness();
	const [outerFuc, setOuterFuc] = useState<IOuterFunc | null>(defaultOutFunc);

	const [tools, setTools] = useSyncState(getTools('base'));

	const [chiefs, setChiefs] = useSyncState<ChiefsProps[]>([]);

	const [serviceMonitoringView, setServiceMonitoring] = useSyncState<boolean>(false);

	const [roomId, setRoomId] = useSyncState<string>('');

	const [isJoinSession, setIsJoinSession] = useSyncState<boolean>(false);

	const [loading, setLoading] = useSyncState<boolean>(false);

	useEffect(() => {
		getAgentBtnTools();
	}, [AgentService.token]);

	useEffect(() => {
		const { ignoreTools = [] } = AgentService.configure.preferenceSettings;
		if (ignoreTools.length > 0) {
			let filtered = [];
			for (const tool of tools()) {
				console.log(tool);

				if (!ignoreTools.includes(tool.id)) {
					filtered.push(tool);
				}
			}
			setTools(filtered);
		}
	}, [AgentService.configure]);

	useEffect(() => {
		if (AgentService.isIMSession) {
			const haveTools: string[] = [IToolsProps.END_SESSION, IToolsProps.TRANSFER, IToolsProps.INVITE];
			setTools(tools().filter(item => haveTools.includes(item.type)));
		} else {
			getAgentBtnTools();
		}
	}, [AgentService.isIMSession]);

	const getAgentBtnTools = () => {
		const { token, configure } = AgentService;
		const { ignoreTools = [] } = configure.preferenceSettings;
		if (token) {
			getAgentTools().then(resp => {
				if (resp) {
					// 对排序结果与本地菜单项合并
					const base = getTools('base');
					let missed = [];
					let sorted = [];
					const longList = base.length > resp.length ? base : resp;
					const shortList = base.length <= resp.length ? base : resp;
					for (const tool of longList) {
						if (ignoreTools.includes(tool.id)) {
							continue;
						}
						const found = shortList.find((item: any) => item.id == tool.id);
						if (!found) {
							missed.push(tool);
						} else {
							sorted.push(tool);
						}
					}

					const _tools = updateToolsText(sorted.concat(missed));
					setTools(_tools);
				} else {
					setTools(getTools('base').filter(item => !ignoreTools.includes(item.id)));
				}
			});
		}
	};

	const getAgentTools = async () => {
		try {
			const { data } = await getAgentProfile();
			if (data && data.profile) {
				return data.profile;
			} else {
				return null;
			}
		} catch (error) {
			console.log(error);
			return null;
		}
	};

	// 结束会话
	const onEndSession = async (type?: string) => {
		let humanAgentCount = 0;
		if (AgentService.isIMSession) {
			humanAgentCount = AgentService.sessionMembers?.filter(item => item.role === 'agent').length || 0;
		} else {
			const agents = streams().filter(item => item.role === 'agent' && !item.isRobot);
			humanAgentCount = agents.length;
		}
		console.log('humanAgentCount', streams(), humanAgentCount);
		
		await AgentService.hangup({ code: 200, reason: 'noraml', type: type || (humanAgentCount > 1 ? 'multiple' : '') });
		setMenuState(prevState => ({ ...prevState, endSessionView: false, showTransfer: false }));
	};

	// 坐席转接
	const transferAgentInit = async (
		option: { agentId: any; service: number | undefined; bizSceneName: string | undefined; type: string; userData: any; filter: never[] },
		transferReason: { reason: string }
	) => {
		if (AgentService.isIMSession && (await getAgentIdIsRobot(option.agentId))) {
			Message.warning(t('im-session-not-transfer-robot-agent'));
			return;
		}
		try {
			const data = await transferBizscenario(option);
			onEndSession(option.type === 'transfer-agent' ? 'transfer' : '');
			console.log('transfer success', data);
		} catch (error) {
			console.log('transfer agent error', error);
		}
	};

	//三方
	const inviteOtherInit = async (option: any) => {
		//三方邀请这个人已存在会话中
		if (streams().find(item => item.userName === option.agentId && item.label.includes('agent')) || audioStreams().find(item => item.userName === option.agentId)) {
			Message.warning(t('agent-existence-session-invite-error'));
			return;
		}
		if (AgentService.isIMSession && (await getAgentIdIsRobot(option.agentId))) {
			Message.warning(t('im-session-not-invite-robot-agent'));
			return;
		}
		console.log(option);
		inviteOther(option);
	};

	//获取当前是否有正在进行的业务指令
	const hasProgressTask = () => {
		const tasks = [...BusinessTaskMap.BusinessQuene.values()];
		let flag = false;
		tasks.forEach(item => {
			if (item.status === IBusinessStatus.IN_PROGRESS && !['regionalScreenRecording', 'recordScreen'].includes(item.name)) {
				flag = true;
				const client = t('current-client');
				Message.warning(`${client}<${item.username}>` + t('ongoing-business-finish-operation'));
				console.warn('hasProgressTask ', item.name);
			}
		});
		return flag;
	};

	//三方坐席
	const inviteAgent = async (data: { agentName?: string; groups?: { id: number; name: string }[] | null; mode: 'agent' | 'groupSkill' }) => {
		const { agentName, groups = null, mode } = data;
		let bizScenario = AgentService.getAllGroupScene().find(item => item.id?.toString() === AgentService.bizScenarioId.toString());
		const userData = { ...session.userData };
		delete userData.callCode;
		let option = {
			agentId: '*',
			service: AgentService.bizScenarioId,
			bizSceneName: bizScenario && bizScenario.name,
			type: '',
			groups: null as any,
			userData: userData || {},
			filter: AgentService.isIMSession
				? [
						{
							attribute: '是否机器人',
							rule: 'ne', //不等于
							value: 'true'
						}
				  ]
				: []
		};
		option.type = 'invite-multiple';

		if (mode === 'agent') {
			if (!agentName) {
				setMenuState(prevState => ({ ...prevState, inviteAgentError: '* ' + t('select-transfer-invite-placeholder') }));
				return;
			}
			if (agentName === AgentService.user?.userName) {
				setMenuState(prevState => ({ ...prevState, inviteAgentError: '*' + t('no-invite-me') }));
				return;
			}
			if (agentName && !(await getAgentNameIsExistence(agentName))) {
				setMenuState(prevState => ({ ...prevState, inviteAgentError: '*' + t('select-agent-non-existent') }));
				return;
			}

			option.agentId = agentName || '';
			option.userData.service = AgentService.bizScenarioId;
			option.service = AgentService.bizScenarioId;
			setMenuState(prevState => ({ ...prevState, inviteAgentError: '', showTransfer: false }));
			inviteOtherInit(option);
		}

		if (mode === 'groupSkill') {
			if (!groups || groups.length === 0) {
				setMenuState(prevState => ({ ...prevState, groupSkillError: '*' + t('plase-select-group-skill') }));
				return;
			}
			option.service = AgentService.bizScenarioId;
			option.userData.service = AgentService.bizScenarioId;
			option.groups = groups;

			console.log('transferOptions:', option);

			setMenuState(prevState => ({ ...prevState, groupSkillError: '', showTransfer: false }));
			inviteOtherInit(option);
		}
	};

	//坐席转接
	const agentTransfer = async (data: IBizScenarioTransfer) => {
		let bizScenario = AgentService.getAllGroupScene().find(item => Number(item.id) === Number(AgentService.bizScenarioId));
		const { agentName, mode, groups } = data;
		let transferReason = {
			reason: t('transferred-to-agent') + agentName
		};
		const userData = { ...session.userData, service: bizScenario?.id };
		delete userData.callCode;
		let option = {
			agentId: '*',
			service: '',
			bizSceneName: '',
			groups: null as any,
			type: '',
			userData: userData || {},
			filter: AgentService.isIMSession
				? [
						{
							attribute: '是否机器人',
							rule: 'ne', //不等于
							value: 'true'
						}
				  ]
				: []
		};

		if (bizScenario) {
			option.bizSceneName = bizScenario.name;
			option.service = bizScenario.id.toString();
		}

		if (mode === 'agent') {
			if (!agentName) {
				setMenuState(prevState => ({ ...prevState, bizScenarioTransferToAgentErrorText: '* ' + t('select-transfer-agent-placeholder') }));
				return;
			}
			if (agentName === AgentService.user?.userName) {
				setMenuState(prevState => ({ ...prevState, bizScenarioTransferToAgentErrorText: '* ' + t('agent-no-transfer-to-me') }));
				return;
			}
			if (!(await getAgentNameIsExistence(agentName))) {
				setMenuState(prevState => ({ ...prevState, bizScenarioTransferToAgentErrorText: '* ' + t('select-agent-non-existent') }));
				return;
			}

			option.agentId = agentName || '';
			option.userData.service = AgentService.bizScenarioId;
			option.service = AgentService.bizScenarioId;
			setMenuState(prevState => ({ ...prevState, showTransfer: false, bizScenarioTransferToScenErrorText: '', bizScenarioTransferToAgentErrorText: '', transferAgentIdErrorText: '' }));
		}

		if (mode === 'groupSkill') {
			if (!groups || groups.length === 0) {
				setMenuState(prevState => ({ ...prevState, bizScenarioTransferGroupSkill: '*' + t('plase-select-group-skill') }));
				return;
			}
			option.service = AgentService.bizScenarioId;
			option.userData.service = AgentService.bizScenarioId;
			option.groups = groups;
		}

		if (hasProgressTask()) {
			setMenuState(prevState => ({ ...prevState, showTransfer: false }));
			return;
		}
		option.type = 'transfer-agent';
		console.log('agentTransfer:', option);

		transferAgentInit(option, transferReason);
		setMenuState(prevState => ({ ...prevState, showTransfer: false, bizScenarioTransferToScenErrorText: '', bizScenarioTransferToAgentErrorText: '', bizScenarioTransferGroupSkill: '' }));
	};

	//场景转接
	const bizScenarioTransfer = async (data: IBizScenarioTransfer) => {
		let { mode, agentName = '', groups = null, transferScene } = data;
		let bizScenario = AgentService.getAllGroupScene().find(item => item.id === transferScene);

		let option = {
			agentId: mode === 'agent' ? agentName : '*',
			service: bizScenario && bizScenario.id,
			bizSceneName: bizScenario && bizScenario.name,
			type: 'transfer-bizscenario',
			groups: null as any,
			userData: { ...session.userData },
			filter: []
		};

		let transferReason = {
			reason: t('transferred-to-agent') + agentName
		};

		if (!bizScenario) {
			setMenuState(prevState => ({ ...prevState, bizScenarioTransferToScenErrorText: `* ${t('business-scenario-selection-please')}` }));
			return;
		}

		// 普通坐席的转接
		if (mode === 'default') {
			transferReason.reason = t('agent-blind-transfer');
		}

		if (mode === 'agent' && (await BizscenarioTransferCheck(agentName, bizScenario))) {
			return;
		}

		if (mode === 'groupSkill' && !groups) {
			setMenuState(prevState => ({ ...prevState, bizScenarioTransferGroupSkill: `* ${t('plase-select-group-skill')}` }));
			return;
		}
		option.groups = groups;
		option.userData.service = bizScenario.id;
		option.service = bizScenario.id;
		if (hasProgressTask()) {
			setMenuState(prevState => ({ ...prevState, showTransfer: false }));
			return;
		}
		setMenuState(prevState => ({ ...prevState, showTransfer: false, bizScenarioTransferToScenErrorText: '', bizScenarioTransferGroupSkill: '', bizScenarioTransferToAgentErrorText: '' }));

		console.log('bizScenarioTransfer:', option);

		transferAgentInit(option, transferReason);
	};

	const BizscenarioTransferCheck = async (agentName: string, bizScenario: any) => {
		let flag = false;
		if (!agentName) {
			setMenuState(prevState => ({ ...prevState, bizScenarioTransferToAgentErrorText: `* ${t('select-transfer-agent-placeholder')}` }));
			flag = true;
			return flag;
		}
		if (agentName !== '*' && !(await getAgentNameIsExistence(agentName))) {
			setMenuState(prevState => ({ ...prevState, bizScenarioTransferToAgentErrorText: `* ${t('select-agent-non-existent')}` }));
			flag = true;
			return flag;
		}
		if (agentName !== '*' && agentName && bizScenario) {
			setMenuState(prevState => ({ ...prevState, bizScenarioTransferToAgentErrorText: '' }));
		}
		return flag;
	};

	//获取该坐席是否是机器人坐席
	const getAgentIdIsRobot = async (name: string) => {
		try {
			const { data } = await getAgentNameIsRobot(AgentService.user?.org ? AgentService.user?.org : '', name);
			console.log(data, 'getAgentIdIsRobot success');
			return data.isRobot;
		} catch (error) {
			console.log(error, 'getAgentIdIsRobot error');
			return false;
		}
	};

	//获取该agentName所绑定的业务场景
	const getAgentNameIsExistence = async (agentName: string) => {
		try {
			const { data } = await agentIdIsExistence(agentName);
			console.log(data, 'getAgentNameIsExistence success');
			return true;
		} catch (error) {
			console.log(error, 'getAgentNameIsExistence error');
			return false;
		}
	};

	//判断坐席是否绑定了业务场景对应的分组
	const agentIdIsBindBizScenario = async (agentName: string, scenId: string) => {
		try {
			const { data } = await agentIsBoundBizscenarios(agentName, scenId);
			console.log(data, 'agentIdIsBindBizScenario success');
			return data;
		} catch (error) {
			console.log(error, 'agentIdIsBindBizScenario error');
			return false;
		}
	};

	//判断坐席是否签入了业务场景对应的分组
	const agentIdIsCheckInBizScenario = async (agentName: string, scenId: string) => {
		try {
			const { data } = await agentIsCheckInBizscenarios(agentName, scenId);
			console.log(data, 'agentIdIsCheckInBizScenario success');
			return data;
		} catch (error) {
			console.log(error, 'agentIdIsCheckInBizScenario error');
			return false;
		}
	};

	const onChangeBizScenario = (e: any) => {
		if (e) {
			setMenuState(prevState => ({ ...prevState, transferError: false, bizScenarioTransferToScenErrorText: '' }));
		}
	};

	// 开始标注
	const startMark = async (clientId: string) => {
		try {
			const resp = await screenMark(clientId);
			console.log('start mark success:', resp);
		} catch (error) {
			console.log('start mark error:', error);
		}
	};

	// 结束标注
	const endScreenMark = async (clientId: string) => {
		try {
			const resp = await stopScreenMark(clientId);
			console.log('cancel screen mark success:', resp);
		} catch (error) {
			console.log('cancel screen mark error:', error);
		}
	};

	useEffect(() => {
		if (screenStream().length === 0 && screenId()) {
			endScreenShare(screenId())
				.then(resp => {
					setScreenId('');
				})
				.catch(e => {
					setScreenId('');
				});
		}
		console.log('screenStream:', screenStream());
	}, [screenStream()]);

	const screenShareRenderError = async (label: string) => {
		await endScreenShare(screenId());
		setScreenId('');
	};

	const chooseBusiness = async (type: string) => {
		console.log('chooseBusiness', type);
		if (!session.sessionId) {
			Message.warning(t('no-calls'));
			return;
		}

		let flag = false; //是否存在多个访客
		let customerMembers = AgentService.getCustomerMediaStream();
		console.log('chooseBusiness customerMembers', customerMembers);

		if (customerMembers.length > 1) {
			flag = true;
		} else {
			flag = false;
		}

		//获取当前是否有正在进行的业务指令
		const hasProgressTask = () => {
			const tasks = [...BusinessTaskMap.BusinessQuene.values()];
			let flag = false;
			tasks.forEach(item => {
				if (item.status === IBusinessStatus.IN_PROGRESS && !['regionalScreenRecording', 'recordScreen'].includes(item.name)) {
					flag = true;
					Message.warning(t('current-client') + `<${item.username}>` + t('ongoing-business-finish-operation'));
					console.warn('hasProgressTask ', item.name);
				}
			});
			return flag;
		};

		switch (type) {
			case 'end-session':
				if (hasProgressTask()) {
					setMenuState(prevState => ({ ...prevState, endSessionView: false }));
					return;
				}
				setMenuState(prevState => ({ ...prevState, endSessionView: true }));
				console.log('end-session');
				break;
			case 'screen-shot':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SCREEN_SHOT, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.SCREEN_SHOT, '', [customerMembers[0].clientId]);
				}
				break;
			case 'screen-share':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SCREEN_SHARE, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.SCREEN_SHARE, '', [customerMembers[0].clientId]);
				}
				console.log('screen-share');
				break;
			case 'screen-mark':
				const screen = screenStream().find(item => item.clientId === AgentService.currentAgentStream?.clientId);
				if (!screen) {
					Message.warning(t('NO_SCREEN_SHARE'));
					return;
				}
				console.log(BusinessTaskMap.BusinessQuene);

				const tasks = [...BusinessTaskMap.BusinessQuene.values()];
				tasks.map(item => {
					if (item.name === IBusinessName.SCREEN_SHARE) {
						startMark(item.clientId);
					}
				});
				const clients = tasks.filter(item => item.name === IBusinessName.SCREEN_SHARE).map(item => item.clientId);
				createScreenContainer({
					endScreenMark,
					clients: clients,
					screenStream: screenStream().filter(item => item.clientId === AgentService.user?.clientId),
					screenShareRenderError: screenShareRenderError
				});

				// setBusiness([...business, resp]);

				console.log('screen-mark');
				break;
			case 'transfer':
				await AgentService.fetchAllGroupsWithOrg();
				setMenuState(prevState => ({ ...prevState, showTransfer: true, inviteMode: 'transfer', modalTitle: '转接' }));
				console.log('transfer');
				break;
			case 'invite':
				await AgentService.fetchAllGroupsWithOrg();
				setMenuState(prevState => ({ ...prevState, showTransfer: true, inviteMode: 'invite', modalTitle: '三方' }));
				console.log('invite');
				break;
			case 'start-screen-sync':
				if (screenSyncState().status === 'idle') {
					Message.warning(t('no-screensync-session'));
					return;
				}

				if (!screenSyncState().cmdId) {
					reuqestPages();
					// BusinessTaskMap.updateTaskStatus(screenSyncState().clientId!, IBusinessStatus.IN_PROGRESS, screenSyncState().cmdId);
				} else {
					if (screenSyncState().mode === 'large') {
						setScreenSyncState({ ...screenSyncState(), mode: 'small' });
					} else {
						setScreenSyncState({ ...screenSyncState(), mode: 'large' });
					}
				}

				console.log(screenSyncState);

				break;
			case 'face-compare':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.FACE_COMPARE, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.FACE_COMPARE, '', [customerMembers[0].clientId]);
				}
				break;
			case 'idcard-compare':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.CARD_COMPARE, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.CARD_COMPARE, '', [customerMembers[0].clientId]);
				}
				console.log('idcard-compare');

				break;
			case 'send-link':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_LINK, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_LINK, showCustomerRoleOrName: false }));
				}
				break;
			case 'send-video':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_VIDEO_LINK, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_VIDEO_LINK, showCustomerRoleOrName: false }));
				}
				break;
			case 'snapshot':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SNAP_SHOT, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.SNAP_SHOT, '', [customerMembers[0].clientId]);
				}
				break;
			case 'record-screen':
				console.log(AgentService);

				await sendBusiness(IBusinessName.RECORD_SCREEN, '', [AgentService.user?.clientId!]);
				break;
			case 'get-geo-localtion':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.GET_GEO_LOCATION, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.GET_GEO_LOCATION, '', [customerMembers[0].clientId]);
				}
				break;
			case 'scanner-code':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_SCANNER_CODE, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.SEND_SCANNER_CODE, '', [customerMembers[0].clientId]);
				}
				break;
			// 实时标注
			case 'customer-view-mark':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.CUSTOMER_VIEW_MARK, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.CUSTOMER_VIEW_MARK, '', [customerMembers[0].clientId]);
				}
				break;
			case 'send-sign':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_SIGN, showCustomerRoleOrName: true }));
				} else {
					await sendBusiness(IBusinessName.SEND_SIGN, '', [customerMembers[0].clientId]);
				}
				break;
			case 'send-form':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.FILL_FORM, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.FILL_FORM, showCustomerRoleOrName: false }));
				}
				break;
			case 'send-pdf':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_PDF, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_PDF, showCustomerRoleOrName: false }));
				}
				break;
			case 'send-card-collection':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_CARD_COLLECTION, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_CARD_COLLECTION, showCustomerRoleOrName: false }));
				}
				break;
			case 'shared-whiteboard':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SHARED_WHITEDOARD, showCustomerRoleOrName: true }));
				} else {
					await startWhiteBoard();
					await sendBusiness(IBusinessName.SHARED_WHITEDOARD, '', [customerMembers[0].clientId]);
				}
				break;
			case 'shared-pdf':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SHARED_PDF, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SHARED_PDF, showCustomerRoleOrName: false }));
				}
				break;
			case 'send-variable-collection':
				if (AgentService.customerVariableList.length === 0) {
					Message.normal(t('no-variables-to-collect'));
					return;
				}
				// if (flag) {
				// 	setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_VARIABLE_COLLECTION, showCustomerRoleOrName: true }));
				// } else {
				// 	setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_VARIABLE_COLLECTION, showCustomerRoleOrName: false }));
				// }
				setMenuState(prevState => ({ ...prevState, showVariableView: true }));
				break;
			case 'transcript-of-testimony':
				if (AgentService.transcriptData.length === 0) {
					Message.warning(t('no-configured-scenario-to-initiate'));
					return;
				}
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.TRANSCRIPT_OF_TESTIMONY, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.TRANSCRIPT_OF_TESTIMONY, showCustomerRoleOrName: false }));
				}
				break;
			case 'send-video-collection':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_VIDEO_COLLECTION, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showSendCommand: true, sendCommandModalType: IBusinessName.SEND_VIDEO_COLLECTION, showCustomerRoleOrName: false }));
				}
				break;
			case 'regional-screen-recording':
				if (!isChrome104Plus()) {
					return;
				}
				await sendBusiness(IBusinessName.REGIONAL_SCREEN_RECORDING, '', [AgentService.user?.clientId!]);
				console.log('regional-screen-recording');
				break;
			case 'knowledge-base':
				if (flag) {
					setMenuState(prevState => ({ ...prevState, showKnowledgeBase: true, sendCommandModalType: IBusinessName.SEND_KNOWLEDGE_BASE, showCustomerRoleOrName: true }));
				} else {
					setMenuState(prevState => ({ ...prevState, showKnowledgeBase: true, sendCommandModalType: IBusinessName.SEND_KNOWLEDGE_BASE, showCustomerRoleOrName: false }));
				}
				break;
			default:
				break;
		}
	};

	return (
		<MenuContext.Provider
			children={children}
			value={{
				bizScenarioTransfer,
				setMenuState,
				setOuterFuc,
				onChangeBizScenario,
				onEndSession,
				chooseBusiness,
				menuState,
				tools,
				setTools,
				chiefs,
				setChiefs,
				serviceMonitoringView,
				setServiceMonitoring,
				roomId,
				setRoomId,
				setIsJoinSession,
				isJoinSession,
				loading,
				setLoading,
				inviteAgent,
				agentTransfer
			}}
		></MenuContext.Provider>
	);
};

const useMenuContext = () => {
	const context = React.useContext(MenuContext);
	if (!context) {
		throw new Error('useMenuContext 必须在 AppProvider 中使用');
	}
	return context;
};

export { useMenuContext, MenuProvider };
